package com.xkw.demo.listener;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
 
@WebListener
public class MyRequestListener implements ServletRequestListener {
 
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println("请求创建了：");
        //将请求开始时间添加到该请求，用于计算本次请求的用时
        String startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date());
        sre.getServletRequest().setAttribute("startTime", startTime);
        try {
            //项目经理说，系统效率需要先慢一点，客户提出优化时再进行优化
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println("请求结束了");
        String uri = ((HttpServletRequest) sre.getServletRequest()).getRequestURL().toString();
        System.out.println("请求路径：" + uri);
        String endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date());
        System.out.println("请求结束时间：" + endTime);
        String startTime = sre.getServletRequest().getAttribute("startTime").toString();
        System.out.println("请求执行时间段：" + startTime + " - " + endTime);
    }
 
}